<template>
    <div class="job-detail-container">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-mask">
            <div class="spinner">加载中...</div>
        </div>

        <!-- 错误状态 -->
        <div v-else-if="error" class="error-message">
            {{ error }}
        </div>

        <div v-else-if="jobData" class="job-content-wrapper">
            <!-- 职位标题、薪资等顶部信息 -->
            <div class="job-header-wrapper">
                <div class="job-header">
                    <div class="job-header-title">
                        <h2 class="job-title">
                            {{ jobData.positionName }}
                        </h2>
                        <span class="job-salary"><!-- 薪资范围，拼接最低和最高月薪 -->
                            {{ jobData.lowestSalaryMonth }}-{{ jobData.highestSalaryMonth }}
                        </span>
                    </div>
                    <!-- 地点、工作经验、学历（根据实际需求格式化） -->
                    <div class="job-meta">
                        <span><i class="el-icon-location-outline"></i>{{ jobData.location }}</span>
                        <span><i class="el-icon-s-cooperation" style="margin-right: 5px;"></i>{{ jobData.positionType
                        }}</span>
                        <span><i class="el-icon-user" style="margin-right: 5px;"></i>{{ formattedEducation }}</span>
                    </div>
                </div>
                <div class="job-header-btn-wrapper">
                    <button v-if="!isCollected" @click="collectJob(jobData.positionId)" class="collect-btn"><i class="el-icon-star-off"
                            style="margin-right: 5px;"></i>收藏</button>
                    <button v-else @click="collectJob(jobData.positionId)" class="collect-btn"><i class="el-icon-star-on"
                            style="margin-right: 5px;"></i>已收藏</button>
                    <button @click="communicate(jobData.userId)" class="communicate-btn">立即沟通</button>
                </div>
            </div>

            <!-- 职位描述等内容区域 -->
            <div class="job-content">
                <section class="job-section">
                    <h3 class="job-section-title">职位描述</h3>
                    <p>{{ jobData.positionDetail }}</p>
                </section>

                <section class="job-section">
                    <h3 class="job-section-title">任职资格</h3>
                    <p>{{ jobData.positionRequire }}</p>
                </section>

                <!-- 公司/发布人信息 -->
                <section class="job-company">
                    <div class="company-info">
                        <img :src="jobData.companyAvatar" alt="公司头像" class="company-avatar" />
                        <div class="company-text">
                            <h4>{{ jobData.companyName }}</h4>
                            <p>发布人：{{ jobData.userName }}</p>
                            <p>角色：{{ jobData.role }}</p>
                        </div>
                    </div>
                </section>

                <!-- 处理可能没有的字段，直接渲染空内容 -->
                <section class="job-section" v-if="jobData.releaseTime">
                    <h3>发布时间</h3>
                    <p>{{ jobData.releaseTime }}</p>
                </section>

                <section class="job-section" v-if="jobData.workYear">
                    <h3>工作年限</h3>
                    <p>{{ jobData.workYear }}</p>
                </section>
            </div>
        </div>

    </div>
</template>

<script>
import { getJobDetail, isCollected, collectJob } from '@/util/seeker_api/job_api'
import { MessageBox } from 'element-ui';
export default {
    name: 'JobDetail',
    props: {
        positionId: {
            type: Number,
            required: true
        }
    },
    data() {
        return {
            jobData: null,
            loading: false, // 添加加载状态
            error: null,    // 添加错误状态
            isCollected: false, // 添加收藏状态
        }
    },
    beforeMount() {
    },
    watch: {
        positionId: {
            handler(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.fetchJobDetail(newVal);
                }
            },
            immediate: true
        }
    },
    methods: {
        async fetchJobDetail(positionId) {
            this.loading = true;
            this.error = null;
            try {
                const response = await getJobDetail(positionId)
                this.jobData = response.data
                //判断是否收藏
                const isCollectedResponse = await isCollected(positionId);
                this.isCollected = isCollectedResponse.data;
                console.log("职位详情", this.jobData)
                console.log(this.isCollected)
            } catch (error) {
                console.error('获取职位详情失败:', error);
                this.error = error.message || '获取职位详情失败';
                this.$message.error('获取职位详情失败')
            } finally {
                this.loading = false;
            }
        },
        // 立即沟通
        async communicate(userId) {
            try {
                // 1. 发送消息
                await this.$store.dispatch('chat/sendChatMessage', {
                    toUserId: userId,
                    fromRole: "seeker",
                    content: "Boss您好，我是求职者，希望能和您进一步沟通",
                    toRole: "recruiter"
                });

                // 消息发送成功后，弹出弹窗
                MessageBox({
                    title: '已向BOSS发送消息',
                    message: `Boss您好，我是求职者，希望能和您进一步沟通<br>如需修改打招呼内容，请在【消息通知 - 设置招呼语】页面修改`,
                    dangerouslyUseHTMLString: true,
                    showCancelButton: true, // 可根据需求决定是否显示取消按钮
                    confirmButtonText: '留在此页',
                    cancelButtonText: '继续沟通',
                    callback: (action) => {
                        if (action === 'cancel') {
                            // 点击“继续沟通”，跳转到聊天页面
                            this.$router.push({
                                name: 'seekerChat',
                                params: { userId }
                            });
                        }
                    }
                });
            } catch (error) {
                console.error('发送消息失败:', error);
                this.$message.error('消息发送失败，请稍后再试');
            }
        },

        // 收藏职位
        async collectJob(positionId) {
            try {
                //判断是否收藏
                if (this.isCollected) {
                    const data = {
                        positionId: positionId,
                        status: false
                    }
                    console.log(data)
                    await collectJob(data);
                    this.isCollected = false
                    this.$message.success('已取消收藏');
                } else {
                    const data = {
                        positionId: positionId,
                        status: true
                    }
                    console.log("已收藏", data)
                    await collectJob(data);
                    this.isCollected = true;
                    this.$message.success('已收藏');
                }
            } catch (error) {
                console.error('操作失败:', error);
                this.$message.error('操作失败，请稍后再试');
            }
        },
    },
    mounted() {
        this.fetchJobDetail(this.positionId)
    },
    computed: {
        formattedEducation() {
            const educationMap = {
                'UNDERGRADUATE': '本科',
                'COLLEGE': '大专',
                'MASTER': '硕士',
                'DOCTOR': '博士',
                'OTHER': '其他'
            };
            return educationMap[this.jobData.education] || this.jobData.education;
        }
    }
}
</script>

<style scoped>
.job-header-wrapper {
    display: flex;
    width: 100%;
    gap: 20px;
}

.job-detail-container {
    padding: 20px;
    width: 95%;
    background: #fff;
    border-radius: 8px;
}

.job-header {
    margin-bottom: 20px;
    flex: 60;
}

.job-header-btn-wrapper {
    flex: 40;
}

.job-header-title {
    display: flex;
    /* 开启flex布局 */
    justify-content: space-between;
    /* 两端对齐（标题左、薪资右） */
    align-items: center;
    /* 垂直居中对齐（避免标题和薪资上下错位） */
    width: 100%;
    margin-bottom: 10px;
}

.job-title {
    font-size: 20px;
    font-weight: bold;
    margin: 0
}

.job-salary {
    color: red;
    /* 薪资颜色设为红色 */
    font-size: 18px;
}

.job-meta {
    display: flex;
    justify-content: flex-start;
    align-items: center;
}

.job-meta span {
    color: #666;
    margin-right: 20px;
}

.collect-btn {
    width: 100px;
    height: 35px;
    border: 1px solid #45bdaf;
    color: #45bdaf;
    background: #fff;
    border-radius: 5px;
    margin: 5px;
}

.communicate-btn {
    width: 100px;
    height: 35px;
    border: 1px solid #45bdaf;
    color: #fff;
    background: #45bdaf;
    border-radius: 5px;
    margin: 5px;
}

.job-section {
    margin-bottom: 20px;
}

.job-section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
    text-align: left;
}

.job-section p {
    text-align: left;
    line-height: 3;
}

.company-info {
    display: flex;
    align-items: center;
}

.company-avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    margin-right: 10px;
}
</style>
